package com.niuwa.p2p.service.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.niuwa.p2p.entity.custservice.CustServiceUser;
import com.niuwa.p2p.entity.custservice.ImportCustRule;
import com.niuwa.p2p.service.custService.ICustServiceService;
import com.niuwa.p2p.service.custService.IImportCustRuleService;
import com.niuwa.p2p.vo.customerservice.CustomerServiceJobUserVo;

/**
 * @author futianliang
 * @date 2015年4月29日
 */
@Component("customerToCustomerServiceJob")
public class CustomerToCustomerServiceJob {

	@Autowired
	private ICustServiceService custServiceService;
	@Autowired
	private IImportCustRuleService ruleService;

	public void run() {
		List<ImportCustRule> list0 = ruleService.getImportCustRuleList();
		if (CollectionUtils.isEmpty(list0)) {
			return;
		}
		List<CustomerServiceJobUserVo> total = new ArrayList<CustomerServiceJobUserVo>();
		ImportCustRule rule = list0.get(0);
		List<CustomerServiceJobUserVo> customerServiceList = custServiceService.getCustomerWithNoAccout();
		if (!CollectionUtils.isEmpty(customerServiceList)) {
			for (CustomerServiceJobUserVo vo : customerServiceList) {
				Date cusCreateTime = vo.getCusCreateTime();
				if (cusCreateTime == null) {
					continue;
				}
				addCustomerToTotal(total, rule, vo, cusCreateTime, true);

			}
		}

		List<CustomerServiceJobUserVo> customerServiceList2 = custServiceService.getAccoutWithOutInvest();
		if (!CollectionUtils.isEmpty(customerServiceList2)) {
			for (CustomerServiceJobUserVo vo : customerServiceList2) {
				Date accountCreateTime = vo.getAccountCreateTime();
				if (accountCreateTime == null) {
					continue;
				}
				addCustomerToTotal(total, rule, vo, accountCreateTime, false);
			}
		}
		if (!CollectionUtils.isEmpty(total)) {
			custServiceService.insertBatch(total);
		}
	}

	private void addCustomerToTotal(List<CustomerServiceJobUserVo> total, ImportCustRule rule, CustomerServiceJobUserVo vo, Date createTime, boolean isRegister) {
		Integer registerDays = rule.getRegisterDays();
		Integer openAcctDays = rule.getOpenAcctDays();
		Long create = createTime.getTime();
		Long now = new Date().getTime();
		int disDays = (int) ((now - create) / (24 * 60 * 60 * 1000));
		String tel = vo.getTel();
		if(tel!=null&&tel.trim().equals("")){
			vo.setTel(null);
		}
		if (isRegister && disDays > registerDays) {
			vo.setCreateTime(new Date());
			vo.setUpdateTime(vo.getCreateTime());
			total.add(vo);
		}
		if (!isRegister && disDays >= openAcctDays) {
			vo.setCreateTime(new Date());
			vo.setCreateTime(vo.getCreateTime());
			total.add(vo);
		}
	}
}
